package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;

    //根据id查询预约详细信息（包括会员姓名、套餐名称、预约基本信息）
    public Map findById(Integer id) {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            try {
                map.put("orderDate", DateUtils.parseDate2String(orderDate));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    //根据地址ID查询此地址是否有预约
    public Integer findAddress(Integer id) {
        return orderDao.findAddress(id);
    }

    //新增预约
    @Override
    public Result addOrder(Map map, List<Integer> setmealIds) throws Exception {
        //对日期进行处理
        Calendar calendar = Calendar.getInstance();
        //先判断选择的预约时间是否可以进行预约
        String _orderDate = (String) map.get("orderDate");
        Date _date = DateUtils.parseString2Date(_orderDate);
        calendar.setTime(_date);
        calendar.add(Calendar.DATE, 1);
        Date date = calendar.getTime();
        //预约日期小于当前日期
        //向数据库中查询该天是否可以预约
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(new SimpleDateFormat("yyyy-MM-dd").format(date)));
        if (orderSetting == null) {
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //可预约人数
        int number = orderSetting.getNumber();
        //已预约人数
        int reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //是否重复预约(手机号(会员)，预约日期，套餐ID)
        String phoneNumber = (String) map.get("phoneNumber");
        //查询该用户是否已注册(未注册自动注册)
        Member member = memberDao.findByTelephone(phoneNumber);
        if (member == null) {
            //该用户未注册，则自动注册
            member = new Member();
            member.setName((String) map.get("name"));
            member.setIdCard((String) map.get("idCard"));
            member.setPhoneNumber(phoneNumber);
            //计算用户年龄
            String age = (String) map.get("age");
            member.setAge(Integer.parseInt(age));
            String _birthday = (String) map.get("birthday");
            Date birthday = DateUtils.parseString2Date(_birthday); //生日少一
            member.setBirthday(birthday);
            member.setSex((String) map.get("sex"));
            member.setRemark((String) map.get("remark"));
            memberDao.add(member);
        }
        //该用户已经注册过了，判断是否重复预约
        Integer memberId = member.getId();
        Order order = new Order();
        order.setMemberId(memberId); //用户ID
        order.setOrderDate(date);    //预约日期
        for (Integer setmealId : setmealIds) {
            order.setSetmealId(setmealId);  //预约套餐ID
            List<Order> list = orderDao.findByCondition(order);
            if (list != null && list.size() > 0) {
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //该用户已注册且未重复预约
        order.setOrderType(Order.ORDERTYPE_TELEPHONE); //电话预约
        order.setOrderStatus(Order.ORDERSTATUS_NO);    //到诊状况
        order.setConfirmStatus(Order.CONFIRMSTATUS_NO);//确定预约状态
        //预约信息添加成功
        orderDao.add(order);
        //修改预约当天的已预约人数
        orderSetting.setReservations(reservations + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        //预约成功
        return new Result(true, MessageConstant.ORDER_SUCCESS);
    }
}
